import React from 'react';
import styles from './style';
import {
    View,
    SafeAreaView,
    Text,
    TextInput,
    Modal,
    TouchableOpacity,
    ScrollView,
    Dimensions,
    Image,
    Alert,
} from 'react-native';
import { getAllPhotosType } from '../../../../common/api/photosType';
import * as Animatable from 'react-native-animatable';
const windowWidth = Dimensions.get('window').width;

import Back from '../../../../common/component/back';
import { launchImageLibrary } from 'react-native-image-picker';
import { createPhotos } from '../../../../common/api/photos';
import { maxImgAdd } from '../../../../util/constants';
// const typeArr = ['摄影', '人物', '风景', '动物', '抽象', '节日'];
export default class AddImg extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            title: '',
            dis: '',
            typeName: '请选择类型',
            showTypePop: false,
            typeArr: [],
            typeId: '',
            selectedImgs: [],
        };
    }
    componentDidMount() {
        this.getData();
    }
    async getData() {
        const types = await getAllPhotosType();
        this.setState({
            typeArr: types,
        });
    }
    closeModal() {
        this.setState({
            showTypePop: false,
        });
        // this.props.closeModal(false);
    }
    selectImg = () => {
        launchImageLibrary(
            { mediaType: 'photo', selectionLimit: maxImgAdd - this.state.selectedImgs.length },
            res => {
                try {
                    this._checkImg(res);
                } catch (e) {
                    return;
                }
                const selectedImgs = this.state.selectedImgs;

                const currentImgs = res.assets.map(it => {
                    return { uri: it.uri, fileName: it.fileName };
                });
                console.log(currentImgs);

                this.setState({ selectedImgs: selectedImgs.concat(currentImgs) });
            }
        );
    };
    changeImg = index => {
        launchImageLibrary({ mediaType: 'photo', selectionLimit: 1 }, res => {
            try {
                this._checkImg(res);
            } catch (e) {
                return;
            }
            const selectedImgs = this.state.selectedImgs;
            selectedImgs[index] = { uri: res.assets[0].uri, fileName: res.assets[0].fileName };
            this.setState({ selectedImgs });
        });
    };
    _checkImg = res => {
        switch (res.errorCode) {
            case 'camera_unavailable':
                throw Alert.alert('相机不可用');
            case 'permission':
                throw Alert.alert('获取相册权限不足');
            case 'others':
                throw Alert.alert('相册获取失败');
            default:
                break;
        }
        if (res.didCancel) {
            throw '用户取消';
        }
    };
    submit = async () => {
        const { title, typeId, dis, selectedImgs } = this.state;
        console.log({ title, typeId, dis, selectedImgs });
        if (selectedImgs.length === 0) {
            return Alert.alert('请选择图片');
        }
        const formData = new FormData();
        formData.append('title', title);
        formData.append('typeId', typeId);
        formData.append('desc', dis);
        for (let index = 0; index < selectedImgs.length; index++) {
            const element = selectedImgs[index];
            formData.append('files', {
                uri: element.uri,
                type: 'multipart/form-data',
                name: element.fileName,
            });
        }
        const res = await createPhotos(formData);
        if (!res) {
            return;
        }
        Alert.alert('上传成功！');
        this.setState({
            title: '',
            dis: '',
            typeName: '请选择类型',
            typeId: '',
            selectedImgs: [],
        });
        console.log(res);
    };
    changeText = item => {
        this.setState({ typeName: item.title, typeId: item._id });
        this.closeModal();
    };
    render() {
        let { navigation } = this.props;
        let { title, typeName, showTypePop, dis, typeArr, selectedImgs } = this.state;
        let iW = (windowWidth - 40) / 3;
        return (
            <SafeAreaView style={{ flex: 1 }}>
                <Back navigation={navigation}></Back>
                <Text style={styles.titileText}>新建/编辑画板</Text>
                <View style={styles.form}>
                    <View style={styles.inputStyle}>
                        <Text style={styles.formTitle}>画板标题</Text>
                        <TextInput
                            placeholder="请输入画板标题"
                            style={styles.inputText}
                            placeholderTextColor="#101010"
                            onChangeText={value => {
                                this.setState({ title: value });
                            }}
                            value={title}
                        />
                    </View>
                    <View style={[styles.inputStyle, { marginTop: 30 }]}>
                        <Text style={styles.formTitle}>类 型</Text>
                        <TouchableOpacity
                            onPress={() => {
                                this.setState({ showTypePop: true });
                            }}
                            underlayColor="#101010"
                            style={[{ width: 260 }]}
                        >
                            <Text style={[{ width: 260, fontSize: 14, color: '#101010' }]}>{typeName}</Text>
                        </TouchableOpacity>
                    </View>
                    <View style={[styles.inputStyle, { marginTop: 30 }]}>
                        <Text style={styles.formTitle}>描 述</Text>
                        <TextInput
                            placeholder="请输入画板描述"
                            style={[styles.inputText, { marginTop: -5 }]}
                            multiline={true}
                            placeholderTextColor="#101010"
                            maxLength={50}
                            onChangeText={value => {
                                this.setState({ dis: value });
                            }}
                            value={dis}
                        />
                        <Text style={styles.formTitle}>{dis.length}/50</Text>
                    </View>
                </View>
                <View style={styles.imgGroup}>
                    {selectedImgs.map((it, index) => {
                        return (
                            <TouchableOpacity onPress={() => this.changeImg(index)} key={index}>
                                <View style={[styles.imgContainer, { width: iW, height: iW }]}>
                                    <Image style={styles.img} source={it} />
                                </View>
                            </TouchableOpacity>
                        );
                    })}

                    {selectedImgs.length < maxImgAdd && (
                        <TouchableOpacity onPress={this.selectImg}>
                            <View style={[styles.addIconContainer, { width: iW, height: iW }]}>
                                <Image style={styles.addImg} source={require('../../img/add.png')} />
                            </View>
                        </TouchableOpacity>
                    )}
                </View>
                <View style={styles.buttonGroup}>
                    <TouchableOpacity onPress={this.submit}>
                        <Animatable.View style={[styles.viewBorder, styles.saveButton]} animation="slideInUp">
                            <Text style={styles.textSave}>保存</Text>
                        </Animatable.View>
                    </TouchableOpacity>
                </View>
                <Modal
                    transparent={true}
                    visible={showTypePop}
                    animationType={'fade'}
                    onRequestClose={() => this.closeModal()}
                >
                    <TouchableOpacity onPress={() => this.closeModal()}>
                        <View style={styles.bgColor}></View>
                    </TouchableOpacity>

                    <View style={styles.scrollText}>
                        {/* 底部滚动 */}
                        <ScrollView showsVerticalScrollIndicator={false}>
                            {typeArr.map((item, index) => {
                                return (
                                    <TouchableOpacity key={index} onPress={() => this.changeText(item)}>
                                        <View style={styles.viewItem}>
                                            <Text>{item.title}</Text>
                                        </View>
                                    </TouchableOpacity>
                                );
                            })}
                        </ScrollView>
                    </View>
                </Modal>
            </SafeAreaView>
        );
    }
}
